package com.lxl.servlet;

import com.lxl.config.SystemConfig;
import com.lxl.message.JsonMsgProvider;
import com.lxl.message.MsgStatus;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@WebServlet(asyncSupported = true)
public class DownloadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");

        //获取所要下载的文件名称
        String filename = request.getParameter("filename");
        String path = request.getParameter("path");
        if (filename == null || path == null) {
            PrintWriter writer = response.getWriter();
            writer.println(new JsonMsgProvider().provideMessage(MsgStatus.REQUEST_ERROR, "Request Error."));
            writer.flush();
            return;
        }

        //下载文件所在目录
        String filePath = SystemConfig.SERVER_ROOT_PATH + path.replace("_", File.separator) + File.separator + filename;
        //通知浏览器以下载的方式打开
        response.addHeader("Content-type", "appllication/octet-stream");
        response.addHeader("Content-Disposition", "attachment;filename="+filename);
        //通知文件流读取文件
        InputStream in = new FileInputStream(filePath);
        //获取response对象的输出流
        OutputStream out = response.getOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        //循环取出流中的数据
        while((len = in.read(buffer)) != -1){
            out.write(buffer,0,len);
        }
        response.getWriter().write(new JsonMsgProvider().provideMessage(MsgStatus.SUCCESS, null));
    }
}
